package com.mjk.common.tools.lock.distrib.impl;


import com.mjk.common.tools.lock.distrib.DistributedLock;
import com.mjk.common.util.ObjectUtils;
import org.redisson.Redisson;
import org.redisson.api.RLock;

import java.util.concurrent.TimeUnit;
/**
 * redisson锁
 * @author Administrator
 *
 */
public class RedisDistributedLock implements DistributedLock {
    /**
     * 锁的超时时间 默认10秒
     */
    private final int TIMEOUT = 10;
	private RLock lock;
	
	private final Redisson redisson;

	public RedisDistributedLock(Redisson redisson) {
		super();
		this.redisson = redisson;
    }

    /**
     * 分布式锁 上锁
     * @param key
     * @return
	 */
	public boolean lock(String key){
		if(ObjectUtils.isEmpty(this.redisson)) {
			return true;
		}
		lock = this.redisson.getLock(key);
        lock.lock(TIMEOUT, TimeUnit.SECONDS);//会阻塞
        return true;
    }

    /**
     * 分布式锁上锁 带超时时间
     *
     * @param key
     * @param timeout
     * @return
     */
    public boolean lock(String key, int timeout) {
        if (ObjectUtils.isEmpty(this.redisson)) {
            return true;
        }
        lock = this.redisson.getLock(key);
        if (timeout > 0)
            lock.lock(timeout, TimeUnit.SECONDS);//会阻塞
		return true;
	}


	public void releaseLock(String key) {
        if (ObjectUtils.isEmpty(this.redisson)) {
            return;
        }
        if (lock == null) {
            return;
        }
        if (lock.isLocked() && lock.isHeldByCurrentThread())
		 	lock.unlock();
    }
}
